package com.thlws.java.proxy.dynamic_cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author HanleyTang
 * @date 2018-12-04
 */
public class CglibProxy<T> implements MethodInterceptor {

    private T target;

    public CglibProxy(T target) {
        this.target = target;
    }


    public T createProxyInstance(){
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        enhancer.setCallback(this);
        return (T) enhancer.create();
    }

    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

        System.out.println("--------cglib调用前-----");
        Object result = methodProxy.invokeSuper(o, args);
        System.out.println("--------cglib调用后-----");
        return result;
    }
}
